package com.kyz.speechsdk.engine.abstracts;


import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.kyz.speechsdk.engine.entity.EngineResult;
import com.kyz.speechsdk.utlis.StringFilter;


/**
 * 语义理解基类，负责管理语义理解引擎顺序
 * create by ZhongZihao on 2020/12/29
 */
public abstract class BaseUnderstandingEngine {
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    protected BaseUnderstandingEngine nextEngine;

    //设置下个处理引擎
    public void setNextEngine(BaseUnderstandingEngine engine) {
        this.nextEngine = engine;
    }

    /**
     * 语义理解
     *
     * @param text              需要理解的文本
     * @param isChainUnderstand 如果为true,则当前引擎找不到答案会继续查找下一个引擎的答案
     */
    protected abstract void requestTextUnderstand(String text, boolean isChainUnderstand);

    public void onTextUnderstand(String text) {
        toUnderstand(text, true);
    }

    public void onSingleEngineTextUnderstand(String text) {
        toUnderstand(text, false);
    }

    private void toUnderstand(String text, boolean isChainUnderstand) {
        if (!TextUtils.isEmpty(text)) {
            String fText = StringFilter.filterSpecCharRec(text);
            if (!TextUtils.isEmpty(fText) && fText.length() >= 2) {
                requestTextUnderstand(text, isChainUnderstand);
            }
        }
    }


    protected UnderstandResultCallback resultCallback;

    public void setUnderstandResultCallback(UnderstandResultCallback resultCallback) {
        this.resultCallback = resultCallback;
        if (nextEngine != null) {
            this.nextEngine.setUnderstandResultCallback(resultCallback);
        }
    }

    //子类返回结果回调
    protected void onEngineResult(EngineResult result) {
        if (resultCallback != null) {
            mainHandler.post(() -> resultCallback.onResult(result));
        }
    }

    protected void nextEngineChainTextUnderstand(String text) {
        if (nextEngine != null) {
            nextEngine.onTextUnderstand(text);
        }
    }

    public void destoryEngine() {
        if (nextEngine != null) {
            nextEngine.destoryEngine();
        }
    }

}
